package com.qqtech.qquan.homemaking.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.community.model.CommunityBase;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.delivery.enums.DeliveryOrderStatusDictEnum;
import com.qqtech.qquan.delivery.model.DeliveryOrderQuery;
import com.qqtech.qquan.delivery.service.DeliveryOrderService;
import com.qqtech.qquan.homemaking.enums.HomemakingBaseAuditStatusDictEnum;
import com.qqtech.qquan.homemaking.enums.HomemakingBaseConst;
import com.qqtech.qquan.homemaking.enums.HomemakingBaseIsShowDictEnum;
import com.qqtech.qquan.homemaking.enums.HomemakingBaseStatusDictEnum;
import com.qqtech.qquan.homemaking.enums.HomemakingItemStatusDictEnum;
import com.qqtech.qquan.homemaking.enums.HomemakingPubitemStatusDictEnum;
import com.qqtech.qquan.homemaking.enums.HomemakingTypeStatusDictEnum;
import com.qqtech.qquan.homemaking.model.HomemakingBase;
import com.qqtech.qquan.homemaking.model.HomemakingBaseQuery;
import com.qqtech.qquan.homemaking.model.HomemakingBaseVo;
import com.qqtech.qquan.homemaking.model.HomemakingItem;
import com.qqtech.qquan.homemaking.model.HomemakingItemVo;
import com.qqtech.qquan.homemaking.model.HomemakingPubitemVo;
import com.qqtech.qquan.homemaking.model.HomemakingTimeVo;
import com.qqtech.qquan.homemaking.model.HomemakingTypeVo;
import com.qqtech.qquan.homemaking.service.HomemakingBaseService;
import com.qqtech.qquan.homemaking.service.HomemakingItemService;
import com.qqtech.qquan.homemaking.service.HomemakingOrderService;
import com.qqtech.qquan.homemaking.service.HomemakingPubitemService;
import com.qqtech.qquan.homemaking.service.HomemakingSysDictService;
import com.qqtech.qquan.homemaking.service.HomemakingTimeService;
import com.qqtech.qquan.homemaking.service.HomemakingTypeService;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayStatusDictEnum;
import com.qqtech.qquan.order.model.OrderBaseQuery;
import com.qqtech.qquan.order.service.OrderBaseService;
import com.qqtech.qquan.pub.service.PubFeedbackService;
import com.qqtech.qquan.sys.service.SysAreaService;
import com.qqtech.qquan.user.model.UserAddress;
import com.qqtech.qquan.user.model.UserAuthVo;
import com.qqtech.qquan.user.model.UserLoginVo;
import com.qqtech.qquan.user.service.UserAddressService;
import com.qqtech.qquan.user.service.UserAuthService;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserValueService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/homemaking/base")
public class HomemakingBaseController extends
		BaseWebController<HomemakingBase, HomemakingBaseQuery> {
	@Resource
	private HomemakingBaseService homemakingBaseService;

	@Resource
	private HomemakingItemService homemakingItemService;

	@Resource
	private HomemakingPubitemService homemakingPubitemService;

	@Resource
	private HomemakingTimeService homemakingTimeService;

	@Resource
	private HomemakingTypeService homemakingTypeService;

	@Resource
	private SysAreaService sysAreaService;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private UserAuthService userAuthService;

	@Resource
	private PubFeedbackService pubFeedbackService;

	@Resource
	private HomemakingOrderService homemakingOrderService;

	@Resource
	private HomemakingSysDictService homemakingSysDictService;

	@Resource
	private OrderBaseService orderBaseService;

	@Resource
	private DeliveryOrderService deliveryOrderService;

	@Resource
	private UserValueService userValueService;
	
	@Resource
	private UserAddressService userAddressService;
	@Resource
	private CommunityBaseService communityBaseService;

	@Override
	protected BaseService<HomemakingBase> getBaseService() {
		return homemakingBaseService;
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public Result list(@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		Pageable pageKit = new PageKit(homemakingBaseQuery.getPage(),
				new PageOrder(Direction.ASC, "id"));
		List<HomemakingBase> fieldList = homemakingBaseService.queryList(
				homemakingBaseQuery, pageKit);
		result.put("fieldList", fieldList);
		return result;
	}

	/**
	 * 分页查询
	 * 
	 * @param homemakingBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/page")
	@ResponseBody
	public Result page(@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		if (homemakingBaseQuery == null) {
			result.addErr("参数不能为空");
		} else if (homemakingBaseQuery.getX() == null
				&& homemakingBaseQuery.getCommunityId() == null) {
			result.addErr("请选择定位");
		}
		if (!result.checkForm()) {
			return result;
		}

		if (homemakingBaseQuery.getFirstTypeId() != null
				&& homemakingBaseQuery.getTypeId() != null) {
			homemakingBaseQuery.setFirstTypeId(null);
		}
		Pageable pageKit = null;
		Page<HomemakingBaseVo> page = null;
		if (homemakingBaseQuery.getSortType() == null) { // 默认排序，按最新时间
			pageKit = new PageKit(homemakingBaseQuery.getPage(), new PageOrder(
					Direction.DESC, "newAt"));
		} else if (homemakingBaseQuery.getSortType() == 1) { // 按距离
			pageKit = new PageKit(homemakingBaseQuery.getPage(), new PageOrder(
					Direction.ASC, "distance"));
		} else if (homemakingBaseQuery.getSortType() == 2) { // 预约人数
			pageKit = new PageKit(homemakingBaseQuery.getPage(), new PageOrder(
					Direction.DESC, "orderedCount"));
		}
		homemakingBaseQuery
				.setAuditStatus(HomemakingBaseAuditStatusDictEnum.THROUGH
						.getCode());
		homemakingBaseQuery.setIsShow(HomemakingBaseIsShowDictEnum.YES
				.getCode());
		homemakingBaseQuery.setStatus(HomemakingBaseStatusDictEnum.OPEN
				.getCode());
		if (homemakingBaseQuery.getCommunityId() == null) {
			homemakingBaseQuery.setDistance(new BigDecimal(5000));
		}else {
			CommunityBase community = communityBaseService.getById(homemakingBaseQuery.getCommunityId());
			if (community != null) {
				homemakingBaseQuery.setX(community.getX());
				homemakingBaseQuery.setY(community.getY());
			}
		}
		page = homemakingBaseService.queryPageListByType(homemakingBaseQuery,
				pageKit);
		result.put("page", page);
		return result;
	}

	@RequestMapping(value = "/typePage")
	@ResponseBody
	public Result typePage(@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		if (homemakingBaseQuery == null) {
			result.addErr("参数不能为空");
		}
		if (!result.checkForm()) {
			return result;
		}
		if (homemakingBaseQuery.getFirstTypeId() != null
				&& homemakingBaseQuery.getTypeId() != null) {
			homemakingBaseQuery.setFirstTypeId(null);
		}
		Pageable pageKit = null;
		Page<HomemakingBaseVo> page = null;
		homemakingBaseQuery.setSize(12);
		if (homemakingBaseQuery.getSortType() == null) { // 默认排序，按最新时间
			pageKit = new PageKit(homemakingBaseQuery.getPage(),
					homemakingBaseQuery.getSize(), new PageOrder(
							Direction.DESC, "newAt"));
		} else if (homemakingBaseQuery.getSortType() == 1) { // 按距离
			pageKit = new PageKit(homemakingBaseQuery.getPage(),
					homemakingBaseQuery.getSize(), new PageOrder(Direction.ASC,
							"distance"));
		} else if (homemakingBaseQuery.getSortType() == 2) { // 预约人数
			pageKit = new PageKit(homemakingBaseQuery.getPage(),
					homemakingBaseQuery.getSize(), new PageOrder(
							Direction.DESC, "orderedCount"));
		}
		homemakingBaseQuery.setDistance(new BigDecimal(30000));
		page = homemakingBaseService.queryPageListByType(homemakingBaseQuery,
				pageKit);
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		map.put("totalPages", page.getTotalElements());
		Map<String, Object> one = new HashMap<String, Object>();
		int t = 0;
		for (int i = 0; i < page.getContent().size(); i++) {
			HomemakingBaseVo vo = page.getContent().get(i);
			if (i % 3 == 0) {
				t = 0;
				one = new HashMap<String, Object>();
				list.add(one);
			}
			one.put("id" + t, vo.getId());
			one.put("img" + t, vo.getFileDomain() + vo.getPhotosImg());
			one.put("name" + t, vo.getName());
			one.put("orderedCount" + t, vo.getOrderedCount() + "人预约");
			one.put("distanceStr" + t, vo.getDistanceStr());
			t++;
		}
		if (!list.isEmpty()) {
			Map<String, Object> last = list.get(list.size() - 1);
			if (!last.containsKey("name1")) {
				last.put("name1", "");
			}
			if (!last.containsKey("name2")) {
				last.put("name2", "");
			}
		}
		map.put("content", list);
		result.put("page", map);
		return result;
	}

	/**
	 * 详情
	 * 
	 * @param id
	 *            家政id
	 * @return
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		HomemakingBaseVo homemakingBaseVo = homemakingBaseService
				.getById(homemakingBaseQuery.getId());
		if (homemakingBaseVo != null) {
			List<HomemakingItemVo> itemVoList = homemakingItemService
					.findByBaseId(homemakingBaseQuery.getId(),
							HomemakingItemStatusDictEnum.NORMAL.getCode());
			for (HomemakingItemVo temp : itemVoList) {
				HomemakingPubitemVo pubitemVo = homemakingPubitemService
						.getById(temp.getItemId());
				temp.setPubitemVo(pubitemVo);
			}
			homemakingBaseVo.setHomemakingItemVo(itemVoList);
			HomemakingTypeVo type = homemakingTypeService
					.getById(homemakingBaseVo.getTypeId());
			homemakingBaseVo.setTypeStr(type.getName());

			UserAuthVo userAuth = (UserAuthVo) userAuthService
					.getByUserId(homemakingBaseVo.getCreatorId());
			userAuth.setIdentityCardImg("");
			userAuth.setIdentityCardBackImg("");
			result.put("userAuth", userAuth);
			// 最近一个月的服务次数
			Timestamp now = TimeUtil.now();
			int serviceCount = homemakingOrderService.getServiceCount(
					homemakingBaseVo.getCreatorId(),
					TimeUtil.afterDays(now, -30), now);
			result.put("serviceCount", serviceCount);
			homemakingBaseVo.setFeedbackScoreAvg(pubFeedbackService
					.getScoreAvg(1, homemakingBaseQuery.getId()));
			// 默认地址
			UserAddress userAddressQuery = new UserAddress();
			UserLoginVo userLoginVo = super.getLoginUser();
			if (userLoginVo != null) {
				Integer userId = userLoginVo.getId();
				userAddressQuery.setIsDefault(1);
				userAddressQuery.setCreatorId(userId);
				userAddressQuery.setStatus(1);
				Pageable pageKit = new PageKit(1,1, new PageOrder(Direction.DESC, "id"));
				List<UserAddress> userAddressList =  userAddressService.queryList(userAddressQuery, pageKit);
				if(userAddressList != null && userAddressList.size() > 0){
					result.put("userAddress", userAddressList.get(0));
				}
			}
		}
		result.put("homemakingBaseVo", homemakingBaseVo);
		return result;
	}

	/**
	 * 预约页面
	 * 
	 * @param id
	 *            家政id
	 * @return
	 */
	@RequestMapping(value = "/toOrder")
	@ResponseBody
	public Result toOrder(@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		HomemakingBaseVo homemakingBaseVo = homemakingBaseService
				.getById(homemakingBaseQuery.getId());
		List<HomemakingItemVo> itemVoList = homemakingItemService.findByBaseId(
				homemakingBaseQuery.getId(),
				HomemakingItemStatusDictEnum.NORMAL.getCode());
		for (HomemakingItemVo temp : itemVoList) {
			HomemakingPubitemVo pubitemVo = homemakingPubitemService
					.getById(temp.getItemId());
			temp.setPubitemVo(pubitemVo);
		}
		homemakingBaseVo.setHomemakingItemVo(itemVoList);
		HomemakingTypeVo type = homemakingTypeService.getById(homemakingBaseVo
				.getTypeId());
		homemakingBaseVo.setTypeStr(type.getName());
		result.put("homemakingBaseVo", homemakingBaseVo);
		return result;
	}

	/**
	 * 新增页面初始化
	 * 
	 * @param type
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/toAdd")
	@ResponseBody
	public Result toAdd(Integer typeId) {
		Result result = new Result();
		List<HomemakingPubitemVo> list = homemakingPubitemService.findByTypeId(
				typeId, HomemakingPubitemStatusDictEnum.VALID.getCode());
		result.put("pubitemVoList", list);
		result.put("typeId", typeId);
		return result;
	}

	/**
	 * 新增
	 * 
	 * @param homemakingBase
	 *            家政
	 * @param itemIds
	 *            项目内容id
	 * @param prices
	 *            项目内容价格
	 * @return
	 */
	@VisitAnnt(type = RespEnum.AUTHREAL)
	@RequestMapping(value = "/add")
	@ResponseBody
	public Result add(@RequestBody HomemakingBaseVo homemakingBase) {
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		Result result = new Result();
		if (homemakingBase == null) {
			result.addErr("参数不能为空");
		} else {
			HomemakingTypeVo type = null;
			if (homemakingBase.getTypeId() == null) {
				result.addErr("请选择类别");
			} else {
				type = homemakingTypeService
						.getById(homemakingBase.getTypeId());
				if (type == null || type.getStatus().intValue() == HomemakingTypeStatusDictEnum.INVALID.getCode()) {
					result.addErr("该类别不存在");
				}
			}
			if (!result.checkForm()) {
				return result;
			}
		    if (homemakingBaseService.hasAddHomemakingBaseByType(userId,
					homemakingBase.getTypeId())) {
				result.addErr("你已经发布过该类型的服务");
			} else {
				if (homemakingBase.getCommunityId() == null) {
					result.addErr("请选择社区");
				}
				if (StringUtil.isBlank(homemakingBase.getName())) {
					result.addErr("技能介绍不能为空");
				}
				if (StringUtil.isBlank(homemakingBase.getImg())) {
					result.addErr("请上传技能证书照片");
				}
				if (homemakingBase.getHomemakingItemVo() == null
						|| homemakingBase.getHomemakingItemVo().isEmpty()) {
					result.addErr("服务项目不能为空");
				} else {
					for (HomemakingItemVo ivo : homemakingBase
							.getHomemakingItemVo()) {
						if (ivo.getItemId() == null) {
							result.addErr("服务项目输入有误");
							break;
						}
						// 家电维修的不用考虑价格
						if (type != null && type.getParentId().intValue() != HomemakingBaseConst.JIA_DIAN_WEI_XIU_ID
								&& (ivo.getPrice() == null || ivo.getPrice().compareTo(BigDecimal.ZERO) != 1)) {
							result.addErr("服务项目的价格必须大于0");
							break;
						}
					}
				}
			}
		}
		if (result.checkForm()) {
			homemakingBase.setCreatorId(userId);
			homemakingBase.setDeposit(BigDecimal.ZERO);
			homemakingBase.setRange(4);
			homemakingBase.setOrderedCount(0);
			homemakingBase.setAuditAt(null);
			homemakingBase
					.setAuditStatus(HomemakingBaseAuditStatusDictEnum.WAIT
							.getCode());
			homemakingBase
					.setIsShow(HomemakingBaseIsShowDictEnum.YES.getCode());
			homemakingBase.setStatus(HomemakingBaseStatusDictEnum.OPEN
					.getCode());
			List<HomemakingItem> items = new ArrayList<HomemakingItem>(
					homemakingBase.getHomemakingItemVo().size());
			for (HomemakingItemVo ivo : homemakingBase.getHomemakingItemVo()) {
				HomemakingItem item = new HomemakingItem();
				item.setItemId(ivo.getItemId());
				item.setPrice(ivo.getPrice() == null ? BigDecimal.ZERO : ivo
						.getPrice());
				items.add(item);
			}
			homemakingBase.setRemark(homemakingBase.getName());
			int id = homemakingBaseService.addHomemakingBase(homemakingBase,
					items);
			result.put("id", id);
		}
		return result;
	}

	/**
	 * 我发布的家政服务
	 * 
	 * @param homemakingBaseQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myPage")
	@ResponseBody
	public Result myPage(@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		Result result = new Result();
		homemakingBaseQuery.setCreatorId(userId);
		Pageable pageKit = new PageKit(homemakingBaseQuery.getPage(),
				new PageOrder(Direction.DESC, "newAt"));
		Page<HomemakingBaseVo> page = homemakingBaseService
				.queryPageListAdminByType(homemakingBaseQuery, pageKit);
		result.put("page", page);
		return result;
	}

	/**
	 * 编辑页面初始化
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/toEdit")
	@ResponseBody
	public Result toEdit(@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		HomemakingBaseVo homemakingBaseVo = homemakingBaseService
				.getById(homemakingBaseQuery.getId());
		List<HomemakingItemVo> itemVoList = homemakingItemService.findByBaseId(
				homemakingBaseQuery.getId(),
				HomemakingItemStatusDictEnum.NORMAL.getCode());
		for (HomemakingItemVo temp : itemVoList) {
			HomemakingPubitemVo pubitemVo = homemakingPubitemService
					.getById(temp.getItemId());
			temp.setPubitemVo(pubitemVo);
		}
		homemakingBaseVo.setHomemakingItemVo(itemVoList);
		HomemakingTypeVo type = homemakingTypeService.getById(homemakingBaseVo
				.getTypeId());
		homemakingBaseVo.setTypeStr(type.getName());
		CommunityBase community = communityBaseService.getById(homemakingBaseVo.getCommunityId());
		if (community != null) {
			homemakingBaseVo.setCommunityName(community.getName());
		}
		result.put("homemakingBaseVo", homemakingBaseVo);

		List<HomemakingPubitemVo> pubitemList = homemakingPubitemService
				.findByTypeId(homemakingBaseVo.getTypeId(),
						HomemakingPubitemStatusDictEnum.VALID.getCode());
		result.put("pubitemList", pubitemList);
		result.put("typeParentId", type.getParentId());
		return result;
	}

	/**
	 * 编辑
	 * 
	 * @param homemakingBase
	 * @param itemIds
	 * @param prices
	 * @return
	 */
	@VisitAnnt(type = RespEnum.AUTHREAL)
	@RequestMapping(value = "/edit")
	@ResponseBody
	public Result edit(@RequestBody HomemakingBaseVo homemakingBase) {
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		Result result = new Result();
		HomemakingBaseVo homemakingBaseVo = null;
		if (homemakingBase == null || homemakingBase.getId() == null) {
			result.addErr("参数不能为空");
		} else {
			homemakingBaseVo = homemakingBaseService
					.getById(homemakingBase.getId());
			HomemakingTypeVo type = homemakingTypeService
					.getById(homemakingBaseVo.getTypeId());
			if (homemakingBaseVo.getCreatorId().intValue() != userId) {
				result.addErr("没有权限修改");
			}
			if (!result.checkForm()) {
				return result;
			}
			if (homemakingBase.getHomemakingItemVo() == null
					|| homemakingBase.getHomemakingItemVo().isEmpty()) {
				result.addErr("服务项目不能为空");
			} else {
				for (HomemakingItemVo ivo : homemakingBase
						.getHomemakingItemVo()) {
					if (ivo.getItemId() == null) {
						result.addErr("服务项目输入有误");
						break;
					}
					// 家电维修的不用考虑价格
					if (type != null && type.getParentId().intValue() != HomemakingBaseConst.JIA_DIAN_WEI_XIU_ID
							&& (ivo.getPrice() == null || ivo.getPrice().compareTo(BigDecimal.ZERO) != 1)) {
						result.addErr("服务项目的价格必须大于0");
						break;
					}
				}
			}
			if (StringUtil.isBlank(homemakingBase.getName())) {
				result.addErr("技能介绍不能为空");
			}
			if (homemakingBaseVo.getAuditStatus().intValue() != HomemakingBaseAuditStatusDictEnum.THROUGH
					.getCode()) {
				// 审核通过的就不用再修改技能证书照片
				if (StringUtil.isBlank(homemakingBase.getImg())) {
					result.addErr("请上传技能证书照片");
				}
			}
		}
		if (result.checkForm()) {
			List<HomemakingItem> items = new ArrayList<HomemakingItem>(
					homemakingBase.getHomemakingItemVo().size());
			for (HomemakingItemVo ivo : homemakingBase.getHomemakingItemVo()) {
				HomemakingItem item = new HomemakingItem();
				item.setItemId(ivo.getItemId());
				item.setPrice(ivo.getPrice() == null ? BigDecimal.ZERO : ivo
						.getPrice());
				items.add(item);
			}
			homemakingBase.setRemark(homemakingBase.getName());
			if (homemakingBaseVo.getAuditStatus().intValue() == HomemakingBaseAuditStatusDictEnum.NOT_THROUGH
					.getCode()) {
				homemakingBase.setAuditStatus(HomemakingBaseAuditStatusDictEnum.WAIT.getCode());
			}
			homemakingBaseService.updateHomemakingBase(homemakingBase, items);
			result.put("id", homemakingBase.getId());
		}
		return result;
	}

	/**
	 * 设置状态为营业(可以接单)
	 * 
	 * @param id
	 * @return
	 */
	@VisitAnnt(type = RespEnum.AUTHREAL)
	@RequestMapping(value = "/open")
	@ResponseBody
	public Result open(@RequestBody HomemakingBaseVo homemakingBase) {
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		Result result = new Result();
		HomemakingBaseVo homemakingBaseVo = homemakingBaseService
				.getById(homemakingBase.getId());
		if (homemakingBaseVo == null
				|| homemakingBaseVo.getCreatorId().intValue() != userId) {
			result.addErr("无法操作");
		}
		if (result.checkForm()) {
			HomemakingBase entity = new HomemakingBase(homemakingBase.getId());
			entity.setStatus(HomemakingBaseStatusDictEnum.OPEN.getCode());
			homemakingBaseService.updateById(entity);
		}
		return result;
	}

	/**
	 * 设置状态为停业（不接单）
	 * 
	 * @param id
	 * @return
	 */
	@VisitAnnt(type = RespEnum.AUTHREAL)
	@RequestMapping(value = "/close")
	@ResponseBody
	public Result close(@RequestBody HomemakingBaseVo homemakingBase) {
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		Result result = new Result();
		HomemakingBaseVo homemakingBaseVo = homemakingBaseService
				.getById(homemakingBase.getId());
		if (homemakingBaseVo == null
				|| homemakingBaseVo.getCreatorId().intValue() != userId) {
			result.addErr("无法操作");
		}
		if (result.checkForm()) {
			HomemakingBase entity = new HomemakingBase(homemakingBase.getId());
			entity.setStatus(HomemakingBaseStatusDictEnum.CLOSE.getCode());
			homemakingBaseService.updateById(entity);
		}
		return result;
	}

	/**
	 * 根据地点和选择的时间 获取服务人员数量
	 * 
	 * @param homemakingBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/getCanServiceMemberCount")
	@ResponseBody
	public Result getCanServiceMemberCount(
			@RequestBody HomemakingBaseVo homemakingBaseVo) {
		Result result = new Result();
		int count = 0;
		if (homemakingBaseVo != null && homemakingBaseVo.getCommunityId() != null
				&& homemakingBaseVo.getServiceDateStr() != null
				&& homemakingBaseVo.getServiceHourStr() != null
				&& homemakingBaseVo.getTypeId() != null) {
			if (homemakingBaseVo.getHomemakingPubitemVos() != null
					&& homemakingBaseVo.getHomemakingPubitemVos().isEmpty()) {
				count = 0;
			} else {
				homemakingBaseVo.setHomemakingTimeVos(new ArrayList<HomemakingTimeVo>());
				//日常保洁有选择时间段的，比如8点开始，需要2小时，就是8点，9点
				if (homemakingBaseVo.getTypeId().intValue() == HomemakingBaseConst.RI_CHANG_BAO_JIE_ID) {
					int hours = homemakingBaseVo.getHomemakingPubitemVos().get(0).getQuantity();
					for (int i = 0; i < hours; i++) {
						int hour = Integer.valueOf(homemakingBaseVo.getServiceHourStr().split(":")[0]) + i;
						HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
						homemakingTimeVoTemp.setServiceDateStr(homemakingBaseVo.getServiceDateStr());
						homemakingTimeVoTemp.setServiceHourStr(hour + ":00");
						homemakingBaseVo.getHomemakingTimeVos().add(homemakingTimeVoTemp);
						homemakingBaseVo.setIsRestMode(2);
					}
				} else {
					HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
					homemakingTimeVoTemp.setServiceDateStr(homemakingBaseVo.getServiceDateStr());
					homemakingTimeVoTemp.setServiceHourStr(homemakingBaseVo.getServiceHourStr());
					homemakingBaseVo.getHomemakingTimeVos().add(homemakingTimeVoTemp);
					homemakingBaseVo.setIsRestMode(1);
				}
				/*homemakingBaseVo.setServiceDateStr(year + "-"
						+ homemakingBaseVo.getServiceDateStr());
				homemakingBaseVo.setServiceHourStr(homemakingBaseVo.getServiceHourStr().split("-")[0]);	*/
				//homemakingBaseVo.setDistance(new BigDecimal(5000));
				homemakingBaseVo
						.setAuditStatus(HomemakingBaseAuditStatusDictEnum.THROUGH
								.getCode());
				homemakingBaseVo.setIsShow(HomemakingBaseIsShowDictEnum.YES
						.getCode());
				homemakingBaseVo.setStatus(HomemakingBaseStatusDictEnum.OPEN
						.getCode());
				count = homemakingBaseService
						.getCountByCanServise(homemakingBaseVo);
			}
		}
		result.put("count", count);
		return result;
	}

	/**
	 * 附近可以预约的服务人员
	 * 
	 * @param homemakingBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/getCanServiceMemberList")
	@ResponseBody
	public Result getCanServiceMemberList(
			@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		if (homemakingBaseQuery != null
				&& homemakingBaseQuery.getCommunityId() != null
				&& homemakingBaseQuery.getServiceDateStr() != null
				&& homemakingBaseQuery.getServiceHourStr() != null
				&& homemakingBaseQuery.getTypeId() != null
				&& (homemakingBaseQuery.getHomemakingPubitemVos() == null || (homemakingBaseQuery
						.getHomemakingPubitemVos() != null && !homemakingBaseQuery
						.getHomemakingPubitemVos().isEmpty()))) {
			Calendar calendar = Calendar.getInstance();
			homemakingBaseQuery.setHomemakingTimeVos(new ArrayList<HomemakingTimeVo>());
			//日常保洁有选择时间段的，比如8点开始，需要2小时，就是8点，9点
			if (homemakingBaseQuery.getTypeId().intValue() == HomemakingBaseConst.RI_CHANG_BAO_JIE_ID) {
				int hours = homemakingBaseQuery.getHomemakingPubitemVos().get(0).getQuantity();
				for (int i = 0; i < hours; i++) {
					int hour = Integer.valueOf(homemakingBaseQuery.getServiceHourStr().split(":")[0]) + i;
					HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
					homemakingTimeVoTemp.setServiceDateStr(homemakingBaseQuery.getServiceDateStr());
					homemakingTimeVoTemp.setServiceHourStr(hour + ":00");
					homemakingBaseQuery.getHomemakingTimeVos().add(homemakingTimeVoTemp);
				}
				homemakingBaseQuery.setIsRestMode(2);
			} else {
				HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
				homemakingTimeVoTemp.setServiceDateStr(homemakingBaseQuery.getServiceDateStr());
				homemakingTimeVoTemp.setServiceHourStr(homemakingBaseQuery.getServiceHourStr());
				homemakingBaseQuery.getHomemakingTimeVos().add(homemakingTimeVoTemp);
				homemakingBaseQuery.setIsRestMode(1);
			}
			/*homemakingBaseQuery.setServiceDateStr(year + "-"
					+ homemakingBaseQuery.getServiceDateStr());
			homemakingBaseQuery.setServiceHourStr(homemakingBaseQuery.getServiceHourStr().split("-")[0]);*/	
			//homemakingBaseQuery.setDistance(new BigDecimal(5000));
			homemakingBaseQuery
					.setAuditStatus(HomemakingBaseAuditStatusDictEnum.THROUGH
							.getCode());
			homemakingBaseQuery.setIsShow(HomemakingBaseIsShowDictEnum.YES
					.getCode());
			homemakingBaseQuery.setStatus(HomemakingBaseStatusDictEnum.OPEN
					.getCode());
			Pageable pageKit = new PageKit(homemakingBaseQuery.getPage(),
					new PageOrder(Direction.ASC, "distance"));
			Page<HomemakingBaseVo> page = homemakingBaseService
					.queryPageListByCanServise(homemakingBaseQuery, pageKit);
			// 计算每个人的具体价格
			if (page != null && page.getContent() != null
					&& homemakingBaseQuery.getHomemakingPubitemVos() != null
					&& !homemakingBaseQuery.getHomemakingPubitemVos().isEmpty()) {
				for (HomemakingBaseVo tempBase : page.getContent()) {
					tempBase.setRemark("");
					List<HomemakingItemVo> itemVoList = homemakingItemService
							.findByBaseId(tempBase.getId(),
									HomemakingItemStatusDictEnum.NORMAL
											.getCode());
					BigDecimal totalPrice = BigDecimal.ZERO;
					for (HomemakingItemVo tempItem : itemVoList) {
						for (HomemakingPubitemVo tempPubitem : homemakingBaseQuery.getHomemakingPubitemVos()) {
							if (tempItem.getItemId().intValue() == tempPubitem.getId().intValue() && tempPubitem.getQuantity() != null) {
								totalPrice = totalPrice.add(tempItem.getPrice().multiply(new BigDecimal(tempPubitem.getQuantity())));
								if (tempBase.getRemark().equals("")) {
									tempBase.setRemark(tempPubitem.getName()+"￥"+tempItem.getPrice().toString() + "X" + tempPubitem.getQuantity().toString());
								} else {
									tempBase.setRemark(tempBase.getRemark() + "\r\n" + tempPubitem.getName()+"￥"+tempItem.getPrice().toString() + "X" + tempPubitem.getQuantity().toString());
								}
								break;
							}
						}
					}
					if (totalPrice.compareTo(BigDecimal.ZERO) == 1) {
						tempBase.setRemark(tempBase.getRemark() + "\r\n总计：￥" + totalPrice.toString());
					}
				}
			}
			result.put("page", page);
		} else {
			result.addErr("参数不能为空");
		}
		return result;
	}
	
	@RequestMapping(value = "/getCanServiceMemberOne")
	@ResponseBody
	public Result getCanServiceMemberOne(
			@RequestBody HomemakingBaseQuery homemakingBaseQuery) {
		Result result = new Result();
		if (homemakingBaseQuery != null
				&& homemakingBaseQuery.getX() != null
				&& homemakingBaseQuery.getY() != null
				&& homemakingBaseQuery.getServiceDateStr() != null
				&& homemakingBaseQuery.getServiceHourStr() != null
				&& homemakingBaseQuery.getTypeId() != null
				&& (homemakingBaseQuery.getHomemakingPubitemVos() == null || (homemakingBaseQuery
						.getHomemakingPubitemVos() != null && !homemakingBaseQuery
						.getHomemakingPubitemVos().isEmpty()))) {
			Calendar calendar = Calendar.getInstance();
			homemakingBaseQuery.setHomemakingTimeVos(new ArrayList<HomemakingTimeVo>());
			//日常保洁有选择时间段的，比如8点开始，需要2小时，就是8点，9点，10点
			if (homemakingBaseQuery.getTypeId().intValue() == HomemakingBaseConst.RI_CHANG_BAO_JIE_ID) {
				int hours = homemakingBaseQuery.getHomemakingPubitemVos().get(0).getQuantity();
				for (int i = 0; i <= hours; i++) {
					int hour = Integer.valueOf(homemakingBaseQuery.getServiceHourStr().split(":")[0]) + i;
					HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
					homemakingTimeVoTemp.setServiceDateStr(homemakingBaseQuery.getServiceDateStr());
					homemakingTimeVoTemp.setServiceHourStr(hour + ":00");
					homemakingBaseQuery.getHomemakingTimeVos().add(homemakingTimeVoTemp);
				}
			} else {
				HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
				homemakingTimeVoTemp.setServiceDateStr(homemakingBaseQuery.getServiceDateStr());
				homemakingTimeVoTemp.setServiceHourStr(homemakingBaseQuery.getServiceHourStr());
				homemakingBaseQuery.getHomemakingTimeVos().add(homemakingTimeVoTemp);
			}
			/*homemakingBaseQuery.setServiceDateStr(year + "-"
					+ homemakingBaseQuery.getServiceDateStr());
			homemakingBaseQuery.setServiceHourStr(homemakingBaseQuery.getServiceHourStr().split("-")[0]);*/	
			homemakingBaseQuery.setDistance(new BigDecimal(5000));
			homemakingBaseQuery
					.setAuditStatus(HomemakingBaseAuditStatusDictEnum.THROUGH
							.getCode());
			homemakingBaseQuery.setIsShow(HomemakingBaseIsShowDictEnum.YES
					.getCode());
			homemakingBaseQuery.setStatus(HomemakingBaseStatusDictEnum.OPEN
					.getCode());
			Pageable pageKit = new PageKit(1,1,
					new PageOrder(Direction.ASC, "distance"),new PageOrder(Direction.DESC, "feedbackScoreAvg"));
			Page<HomemakingBaseVo> page = homemakingBaseService
					.queryPageListByCanServise(homemakingBaseQuery, pageKit);
			// 计算每个人的具体价格
			if (page != null && page.getContent() != null
					&& homemakingBaseQuery.getHomemakingPubitemVos() != null
					&& !homemakingBaseQuery.getHomemakingPubitemVos().isEmpty()) {
				for (HomemakingBaseVo tempBase : page.getContent()) {
					tempBase.setRemark("");
					List<HomemakingItemVo> itemVoList = homemakingItemService
							.findByBaseId(tempBase.getId(),
									HomemakingItemStatusDictEnum.NORMAL
											.getCode());
					BigDecimal totalPrice = BigDecimal.ZERO;
					for (HomemakingItemVo tempItem : itemVoList) {
						for (HomemakingPubitemVo tempPubitem : homemakingBaseQuery.getHomemakingPubitemVos()) {
							if (tempItem.getItemId().intValue() == tempPubitem.getId().intValue() && tempPubitem.getQuantity() != null) {
								totalPrice = totalPrice.add(tempItem.getPrice().multiply(new BigDecimal(tempPubitem.getQuantity())));
								if (tempBase.getRemark().equals("")) {
									tempBase.setRemark(tempPubitem.getName()+"￥"+tempItem.getPrice().toString() + "X" + tempPubitem.getQuantity().toString());
								} else {
									tempBase.setRemark(tempBase.getRemark() + "\r\n" + tempPubitem.getName()+"￥"+tempItem.getPrice().toString() + "X" + tempPubitem.getQuantity().toString());
								}
								break;
							}
						}
					}
					if (totalPrice.compareTo(BigDecimal.ZERO) == 1) {
						tempBase.setRemark(tempBase.getRemark() + "\r\n总计：￥" + totalPrice.toString());
					}
				}
				result.put("member", page.getContent().get(0));
			}
		} else {
			result.addErr("参数不能为空");
		}
		return result;
	}

	/**
	 * 获取技能数量，卖家：已付款未发货（等待服务）数量，买家：已发货（已服务）,待签收的代收代送订单
	 * 
	 * @return
	 * @throws OrderException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/getCount")
	@ResponseBody
	public Result getCount() throws OrderException {
		Result result = new Result();
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		int homemakingBaseCount = homemakingBaseService
				.myHomemakingBaseCount(userId);
		OrderBaseQuery sellerOrder = new OrderBaseQuery();
		sellerOrder.setSellerId(userId);
		sellerOrder.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED
				.getCode());// 未完成
		sellerOrder.setPayStatus(OrderBasePayStatusDictEnum.PAYED.getCode());// 已付款
		sellerOrder.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.UNSEND
				.getCode());// 未发货
		int waitSendCount = orderBaseService.queryCount(sellerOrder);
		OrderBaseQuery buyerOrder = new OrderBaseQuery();
		buyerOrder.setBuyerId(userId);
		buyerOrder.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED
				.getCode());// 未完成
		buyerOrder.setPayStatus(OrderBasePayStatusDictEnum.PAYED.getCode());// 已付款
		buyerOrder.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.SENDED
				.getCode());// 发货
		int waitReceiptCount = orderBaseService.queryCount(buyerOrder);
		DeliveryOrderQuery deliveryOrder = new DeliveryOrderQuery();
		deliveryOrder.setCreatorId(userId);
		deliveryOrder.setStatus(DeliveryOrderStatusDictEnum.NoSign.getCode());
		int deliveryOrderCount = deliveryOrderService.queryCount(deliveryOrder);
		result.put("homemakingBaseCount", homemakingBaseCount);
		result.put("waitSendCount", waitSendCount);
		result.put("waitReceiptCount", waitReceiptCount);
		result.put("deliveryOrderCount", deliveryOrderCount);
		result.put("totalCount", homemakingBaseCount + waitSendCount
				+ waitReceiptCount + deliveryOrderCount);
		return result;
	}
}
